/**
 * 接口：数据字典
 * @Author: 
 * @Date: 
 * @Copyright：
 */
import { postRequest, getRequest } from '/@/api/config/axios-fun';
import { ApiUtil } from "/@/utils/api";

export const DictAPI = {
  init: () => ({
    id: 0,
    type: null,
    key: null,
    value: null,
    keyName: null,
    grouping: null,
    remark: null,
    editFlag: null,
    displayFlag: null,
    sort: null,
    appId: null,
  }),

  getDict(params) {
    return new Promise((resolve) => {
      getRequest('/dict/getDict', params).then(({ res, data }) => {
        resolve({ ...ApiUtil.cleanGet({ res, data }) });
      });
    });
  },

  listDict(params, appIdFlag = true) {
    return new Promise((resolve) => {
      // if (appIdFlag) {
      //   if (!params) {
      //     params = { appId: getAppInfo().id };
      //   } else if (!params.appId) {
      //     params.appId = getAppInfo().id;
      //   }
      // }
      delete params.appId;
      getRequest("dict/listDict", params).then(({ res, data }) => {
        let list = [],
          pageIndex = 1,
          count = 0;
        if (ApiUtil.isResponseSuccess(data)) {
          list = data.data.data;
          if (data.data) {
            pageIndex = data.data.currentPage;
            count = data.data.count;
          }
        }
        resolve({ res, data, list, pageIndex, count });
      });
    });
  },

  insertDict(params, showMsgFlag = true, msg = '新增') {
    return new Promise((resolve) => {
      postRequest('dict/insertDict', params).then(({ res, data }) => {
        resolve({ ...ApiUtil.cleanGet({ res, data }, showMsgFlag, msg) });
      });
    });
  },

  updateDict(params, showMsgFlag = true, msg = '修改') {
    return new Promise((resolve) => {
      postRequest('dict/updateDict', params).then(({ res, data }) => {
        resolve({ ...ApiUtil.cleanGet({ res, data }, showMsgFlag, msg) });
      });
    });
  },

  deleteDict(params, showMsgFlag = true, msg = '删除') {
    return new Promise((resolve) => {
      postRequest('dict/deleteDict', params, { inDataFlag: false }).then(({ res, data }) => {
        resolve({ ...ApiUtil.cleanGet({ res, data }, showMsgFlag, msg) });
      });
    });
  },

  listDictByTypes(types) {
    return new Promise((resolve) => {
      getRequest('dict/listDict', { type: types, ...ApiUtil.getTotalDataParams() }).then(({ res, data }) => {
        // eslint-disable-next-line prefer-const
        let list = [],
          map = types.split(',').reduce((total, item) => {
            total[item] = [];
            return total;
          }, {});
        if (ApiUtil.isResponseSuccess(data)) {
          list = data.data.data;
          list.forEach((item) => {
            map[item.type].push(item);
          });
        }
        resolve({ res, data, list, map });
      });
    });
  },
};
